<?php

namespace app\web\logic;

use app\common\component\Param;
use app\common\component\ErrorCode;
use app\common\component\Elasticsearch;
use app\web\mongo\ElasticsearchMongo;

/**
 * elasticsearch逻辑层
 * Class ElasticsearchLogic
 * @package app\web\logic
 */
class ElasticsearchLogic
{
    /**
     * 删除最旧的数据
     * @param $elaIdentify
     * @throws \Exception
     */
    private function deleteOldestData($elaIdentify)
    {
        $data = ElasticsearchMongo::getInstance()->find(['ela_identify' => $elaIdentify]);
        if ($data) {
            // 删除mongo数据
            ElasticsearchMongo::getInstance()->del(['id' => $data['id']]);
            // 删除elasticsearch数据
            Elasticsearch::getInstance()->delete('www', 'practice', $data['id']);
        }
    }

    /**
     * 校验每个用户的数据是否达到上限
     * @param $elaIdentify
     */
    private function upperLimit($elaIdentify)
    {
        $num = ElasticsearchMongo::getInstance()->count(['ela_identify' => $elaIdentify]);
        if ($num >= 50) {
            $this->deleteOldestData($elaIdentify);
        }
    }


    /**
     * 添加mongo + elasticsearch数据
     * @throws \Exception
     */
    public function addElasticsearch()
    {
        $this->upperLimit(Param::$validParams['ela_identify']);
        $data = [
            'ip' => $_SERVER['REMOTE_ADDR'],
            'content' => Param::$validParams['content'],
            'ela_identify' => Param::$validParams['ela_identify']
        ];

        $id = ElasticsearchMongo::getInstance()->add($data);
        if (empty($id)) {
            throw new \Exception('添加数据失败', ErrorCode::RESPONSE_FAIL);
        }

        $data['id'] = $id;
        Elasticsearch::getInstance()->add('www', 'practice', $data);
    }

    /**
     * 列表mongo + elasticsearch数据
     * @return array
     */
    public function listElasticsearch()
    {
        $filter = ['ela_identify' => Param::$validParams['ela_identify']];
        $sort = ['id' => 1];

        $mongoData = ElasticsearchMongo::getInstance()->pageList($filter, $sort, 0, 100);
        $hotPhrzseData = Elasticsearch::getInstance()->hotPhrase();
        return ['mongoData' => $mongoData, 'hotPhraseData' => $hotPhrzseData];
    }
}